import PubSub from "pubsub-js";
import React, { Component } from "react";

class Hello extends Component {
  state = {
    count: 1,
  };

  componentDidMount(): void {
    /**
     * PubSub.subscribe 返回值是一个字符串，可以通过 PubSub.unsubscribe(字符串) 取消订阅
     */
    this.stop = PubSub.subscribe("increment", () => {
      console.log("increment");
      this.setState((state) => ({ count: state.count + 1 }));
    });
  }

  componentWillUnmount(): void {
    PubSub.unsubscribe(this.stop);
  }

  render(): React.ReactNode {
    return (
      <div>
        <h2>Hello</h2>
        <button>{this.state.count}</button>
      </div>
    );
  }
}

class World extends Component {
  handleClick = () => {
    PubSub.publish("increment");
  };

  render(): React.ReactNode {
    return (
      <div>
        <h2>World</h2>
        <button onClick={this.handleClick}>点我，修改 Hello 中的 count</button>
      </div>
    );
  }
}

export default class App extends Component {
  state = {
    showHello: true,
  };

  render() {
    return (
      <div>
        <h1>App</h1>
        <button
          onClick={() => {
            this.setState((state) => ({ showHello: !state.showHello }));
          }}
        >
          Toggle
        </button>

        <hr />
        {this.state.showHello && <Hello />}

        <hr />
        <World />
      </div>
    );
  }
}
